package com.zhz.system.controller;

import com.zhz.common.controller.BaseController;
import com.zhz.common.shiro.entity.UserProfileResponse;
import com.zhz.common.tool.mybatisplus.base.core.contract.Page;
import com.zhz.common.tool.mybatisplus.base.core.contract.R;
import com.zhz.model.system.contract.param.UserQueryParam;
import com.zhz.system.biz.UserBizService;
import com.zhz.system.contract.request.*;
import com.zhz.system.contract.response.UserFindAllResponse;
import com.zhz.system.contract.response.UserFindOneResponse;
import com.zhz.system.contract.response.UserLoginResponse;
import com.zhz.system.repository.service.PermissionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 用户控制器
 *
 * @author zhouhengzhe
 * @date 2023/4/3
 */
@Api(tags = "用户管理")
@RestController
@RequestMapping("/sys/user")
public class UserController extends BaseController {

    @Autowired
    private UserBizService userBizService;

    @Autowired
    private PermissionService permissionService;
    //
    //@RequestMapping("/user/upload/{id}")
    //public R upload(@PathVariable String id, @RequestParam(name="file") MultipartFile file ) throws IOException {
    //    //1.调用service保存图片（获取到图片的访问地址（dataUrl | http地址））
    //    String imgUrl = userService.uploadImage(id,file);
    //    //2.返回数据
    //    return R.ok();
    //}

//
//    /**
//     * 导入Excel，添加用户
//     *  文件上传：springboot
//     */
//    @RequestMapping(value="/user/import",method = RequestMethod.POST)
//    public Result importUser(@RequestParam(name="file") MultipartFile file) throws Exception {
//        //1.解析Excel
////        //1.1.根据Excel文件创建工作簿
////        Workbook wb = new XSSFWorkbook(file.getInputStream());
////        //1.2.获取Sheet
////        Sheet sheet = wb.getSheetAt(0);//参数：索引
////        //1.3.获取Sheet中的每一行，和每一个单元格
////        //2.获取用户数据列表
////        List<User> list = new ArrayList<>();
////        System.out.println(sheet.getLastRowNum());
////        for (int rowNum = 1; rowNum<= sheet.getLastRowNum() ;rowNum ++) {
////            Row row = sheet.getRow(rowNum);//根据索引获取每一个行
////            Object [] values = new Object[row.getLastCellNum()];
////            for(int cellNum=1;cellNum< row.getLastCellNum(); cellNum ++) {
////                Cell cell = row.getCell(cellNum);
////                Object value = getCellValue(cell);
////                values[cellNum] = value;
////            }
////            User user = new User(values);
////            list.add(user);
////        }
//
//        List<User> list = new ExcelImportUtil(User.class).readExcel(file.getInputStream(), 1, 1);
//        //3.批量保存用户
//        userService.saveAll(list,companyId,companyName);
//
//        return new Result(ResultCode.SUCCESS);
//    }
//
//    public static Object getCellValue(Cell cell) {
//        //1.获取到单元格的属性类型
//        CellType cellType = cell.getCellType();
//        //2.根据单元格数据类型获取数据
//        Object value = null;
//        switch (cellType) {
//            case STRING:
//                value = cell.getStringCellValue();
//                break;
//            case BOOLEAN:
//                value = cell.getBooleanCellValue();
//                break;
//            case NUMERIC:
//                if(DateUtil.isCellDateFormatted(cell)) {
//                    //日期格式
//                    value = cell.getDateCellValue();
//                }else{
//                    //数字
//                    value = cell.getNumericCellValue();
//                }
//                break;
//            case FORMULA: //公式
//                value = cell.getCellFormula();
//                break;
//            default:
//                break;
//        }
//        return value;
//    }
//

    @PostMapping("/assignRoles")
    @ApiOperation("分配角色")
    public R assignRoles(@RequestBody @Validated UserAssignRoleRequest userAssignRoleRequest) {
        //3.调用service完成角色分配
        userBizService.assignRoles(userAssignRoleRequest);
        return R.ok();
    }

    @PostMapping("/save")
    @ApiOperation("保存用户")
    public R<Void> save(@RequestBody UserSaveRequest userSaveRequest) {
        //1.设置保存的企业id
        userSaveRequest.setCompanyId(companyId)
                .setCompanyName(companyName);
        //2.调用service完成保存企业
        userBizService.save(userSaveRequest);
        //3.构造返回结果
        return R.ok();
    }

    @PostMapping("/page")
    @ApiOperation("查询用户分页列表")
    public R<Page<UserFindAllResponse>> page(@RequestBody UserQueryParam userQueryParam) {
        //1.获取当前的企业id
        userQueryParam.setCompanyId(companyId);
        //2.完成查询
        Page<UserFindAllResponse> userFindAllResponsePage = userBizService.page(userQueryParam);
        return R.ok(userFindAllResponsePage);
    }


    @PostMapping("/findById")
    @ApiOperation("根据ID查询user")
    public R<UserFindOneResponse> findById(@RequestBody UserFindOneRequest userFindOneRequest) {
        return R.ok(userBizService.findById(userFindOneRequest));
    }

    @PostMapping("update")
    @ApiOperation("修改User")
    public R<Void> update(@RequestBody UserUpdateRequest userUpdateRequest) {
        userBizService.update(userUpdateRequest);
        return R.ok();
    }

    @RequiresPermissions(value = "API-USER-DELETE")
    @PostMapping(value = "/delete", name = "API-USER-DELETE")
    @ApiOperation("根据ID删除user")
    public R<Void> delete(@RequestBody UserDeleteRequest userDeleteRequest) {
        userBizService.deleteById(userDeleteRequest);
        return R.ok();
    }
//
//    @RequestMapping(value = "/user/simple", method = RequestMethod.GET)
//    public Result simple() throws Exception {
//        List<UserSimpleResult> list = new ArrayList<>();
//        List<User> users = userService.findAll(companyId);
//        for (User user : users) {
//            list.add(new UserSimpleResult(user.getId(), user.getUsername()));
//        }
//        return new Result(ResultCode.SUCCESS, list);
//    }
//

    /**
     * 用户登录
     * 1.通过service根据mobile查询用户
     * 2.比较password
     * 3.生成jwt信息
     */
    @PostMapping("/login")
    @ApiOperation("登录")
    public R<UserLoginResponse> login(@RequestBody UserLoginRequest userLoginRequest) {
        return R.ok(userBizService.login(userLoginRequest));
    }


    /**
     * 用户登录成功之后，获取用户信息
     * 1.获取用户id
     * 2.根据用户id查询用户
     * 3.构建返回值对象
     * 4.响应
     */
    @PostMapping("/profile")
    @ApiOperation("获取用户信息")
    public R<UserProfileResponse> profile() {
        return R.ok(userBizService.profile());
    }

}
